<template>
  <div class="container">
    <div class="lucky-wheel">
      <div class="wheel-main">
        <img src="../assets/images/del_btn.png" class="del_btn" />
        <div class="arrow_down">
          <div class="raindrops" v-if="isRaindrops"></div>
        </div>
        <!-- 灯泡 -->
        <div class="light_main">
          <img src="../assets/images/light_default.png" class="light_img" />
          <img
            src="../assets/images/light_active.png"
            class="light_img default"
            :style="lightStyle"
          />
        </div>
        <!-- 转盘内容 -->
        <!-- 点击抽奖按钮 -->
        <div class="wheel-pointer" @click="getRotate()"></div>
        <div class="wheel-bg" :style="rotateStyle">
          <div class="prize-list">
            <div
              class="prize-item"
              v-for="(item, index) in prizeList"
              :key="index"
              :style="item.style"
            >
              <!-- <div class="prize-pic">
                <img :src="item.icon" />
              </div> -->
              <div class="prize-type">
                <span :style="{ color: '#F9E853' }">{{ item.prize }}</span
                >元
              </div>
            </div>
          </div>
        </div>
        <!-- 红框区域内容 -->
        <div class="red-bg-wrapper">
          <div class="red-bg">
            <!-- 中奖纪录 -->
            <div class="orange_btn" @click="handelRecord">中奖纪录</div>
            <!-- 走马灯 -->
            <div class="notice"></div>
            <img class="bonus_title" src="../assets/images/bonus_title.png" />
            <div class="gold_box">
              <div class="nums">{{ prizeVal }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 中奖结果 -->
    <div class="winning" v-if="winning">
      <div :style="{ display: 'flex', alignItems: 'center' }">
        <img
          src="../assets/images/congratulations.png"
          :style="{ width: '6.8125rem' }"
        />
        <template v-for="(num, index) in winnerResult">
          <img :key="index" :src="require(`../assets/images/num_${num}.png`)" />
        </template>
        <img src="../assets/images/yuan.png" :style="{ width: '5.09375rem' }" />
      </div>
    </div>
    <!-- 中奖纪录 -->
    <div class="record-container" v-if="record">
      <div class="record-tabs">
        <div
          :class="`tab-item ${active === index ? 'active' : ''}`"
          v-for="(item, index) in tabs"
          :key="index"
          @click="handleTabs(index)"
        >
          <img
            :src="active === index ? item.active_text : item.text"
            :style="item.active_text"
          />
        </div>
      </div>
      <div class="record-content">
        <template v-for="(item, index) in historys">
          <div :key="index" class="content-item">
            <div class="content-left">
              <span class="content_active">{{ item.name }}</span
              >获得奖金池中的<span class="content_active"
                >{{ item.prize }}元现金奖励</span
              >
            </div>
            <!-- <div class="content-right">2020/12/02 14:00:00</div> -->
          </div>
        </template>
      </div>
    </div>
    <div class="toast-mask" v-show="modal" @click="closeToast"></div>

    <!-- 提示框 -->
    <!-- <toast /> -->
  </div>
</template>
<script>
const CIRCLE_ANGLE = 360;
import { getInfo, getHistory, getRotate } from "@/utils/api"; // 接口
// import toast from './toast/index'

// 中奖记录切换内容
const tabs = [
  {
    name: "大奖纪录",
    text: require("../assets/images/record_left_text_default.png"),
    active_text: require("../assets/images/record_left_text_active.png"),
    text_style: { height: "1rem", widt: "2.84375rem" },
  },
  {
    name: "我的纪录",
    text: require("../assets/images/record_right_text_default.png"),
    active_text: require("../assets/images/record_right_text_active.png"),
    text_style: { height: "1rem", widt: "2.84375rem" },
  },
];

const config = {
  // 总旋转时间
  duration: 4000,
  // 旋转圈数
  circle: 8,
  mode: "ease-in-out",
};

export default {
  name: "luckywheel",
  // components: { toast },
  data() {
    return {
      count: 10, // 剩余抽奖次数
      duration: 3000, // 转盘旋转时间
      prizeList: [], // 奖品列表
      rotateAngle: 0, // 旋转角度
      index: 0,
      prize: null,
      modal: false,
      nums: [1, 1, 1, 1, 1],
      tabs,
      active: 0,
      record: false,
      winning: false,
      isRaindrops: false,
      winnerResult: [],
      isLight: false,
      prizeVal: null,
      historys: [],
      winPrize: null,
      isRotate: true, // 是否可以抽奖
    };
  },
  computed: {
    rotateStyle() {
      return `
        -webkit-transition: transform ${this.config.duration}ms ${this.config.mode};
        transition: transform ${this.config.duration}ms ${this.config.mode};
        -webkit-transform: rotate(${this.rotateAngle}deg);
            transform: rotate(${this.rotateAngle}deg);`;
    },
    lightStyle() {
      let style = `
          -webkit-animation: flash ${this.config.duration}ms;
          animation: flash ${this.config.duration}ms`;
      if (this.isLight) {
        return style;
      }
      return "";
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // 初始化一些值
      this.angleList = [];
      // 是否正在旋转
      this.isRotating = false;
      // 基本配置
      this.config = config;
      // 接口请求
      this.getInfo();
    },
    async getInfo() {
      try {
        const res = await getInfo();
        let formatPrizeList = this.formatPrizeList(res.prizeList);
        this.prizeList = formatPrizeList.map((item) => {
          return {
            ...item,
            data: this.setNums(item.prize),
          };
        });
        // this.formatPrizeList(res.prizeList);
        // console.log(this.formatPrizeList(res.prizeList));
        this.prizeVal = res.prizeVal;
      } catch (error) {
        this.$toast(error);
        console.error(error);
      }
    },
    async getHistory(type) {
      try {
        const res = await getHistory(type);
        this.historys = res.list;
      } catch (error) {
        this.$toast(error);
        console.error(error);
      }
    },
    async getRotate() {
      let { isRotate } = this;
      if (!isRotate) return;
      this.isRotate = false;
      try {
        const res = await getRotate();
        this.winPrize = res.winPrize;
        this.prizeVal = res.prizeVal;
        // 请求接口看是否有能抽奖
        res.times >= 1 && this.beginRotate();
      } catch (error) {
        this.$toast(error);
        console.error(error);
        this.isRotate = true;
      }
    },
    handleTabs(i) {
      this.active = i;
      this.getHistory(i);
    },
    // 格式化奖品列表，计算每个奖品的位置
    formatPrizeList(list) {
      // 记录每个奖的位置
      const angleList = [];

      const l = list.length;
      // 计算单个奖项所占的角度 18
      const average = CIRCLE_ANGLE / l;
      // console.log(average);

      const half = average / 2;

      // 循环计算给每个奖项添加style属性
      list.forEach((item, i) => {
        // 每个奖项旋转的位置为 当前 i * 平均值 + 平均值 / 2
        const angle = +(i * average);
        // 增加 style
        item.style = `-webkit-transform: rotate(${angle}deg);
                      transform: rotate(${angle}deg);`;

        // 记录每个奖项的角度范围
        angleList.push(i * average + half);
      });

      this.angleList = angleList;

      return list;
    },
    async beginRotate() {
      let { prizeList, winPrize } = this;
      this.isRaindrops = false;
      this.isLight = true;
      // 添加次数校验

      // if(this.count === 0) return

      // 开始抽奖
      // 这里这里向服务端发起请求，得到要获得的奖
      // 可以返回下标，也可以返回奖品 id，通过查询 奖品列表，最终得到下标

      // 随机获取下标
      // this.index = this.random(this.prizeList.length - 1);

      for (let i in prizeList) {
        let item = prizeList[i];
        if (item.prize === winPrize) {
          this.index = +i - 1;
        }
      }

      // 减少剩余抽奖次数
      // this.count--

      // 开始旋转
      this.rotating();
    },
    random(max, min = 0) {
      return parseInt(Math.random() * (max - min + 1) + min);
    },
    rotating() {
      const { isRotating, angleList, config, rotateAngle, index } = this;

      if (isRotating) return;

      this.isRotating = true;

      // 计算角度
      const angle =
        // 初始角度
        rotateAngle +
        // 多旋转的圈数
        config.circle * CIRCLE_ANGLE -
        // 奖项的角度
        angleList[index] -
        (rotateAngle % CIRCLE_ANGLE) -
        20;

      this.rotateAngle = angle;

      // 旋转结束后，允许再次触发
      setTimeout(() => {
        this.rotateOver();
      }, config.duration + 1000);
    },
    rotateOver() {
      let { prizeList, winPrize, index } = this;
      this.isRotating = false;
      this.isLight = false;
      this.isRotate = true;
      // let len = prizeList.length;
      // let index = this.index !== 0 ? len - this.index : 0;

      // this.prize = prizeList[index];
      this.prize = winPrize;
      this.winnerResult = prizeList[index + 1].data;
      this.modal = true;
      this.winning = true;
      this.isRaindrops = true;
      console.log(this.prize, index);
    },
    //关闭弹窗
    closeToast() {
      this.prize = null;
      this.modal = false;
      this.record = false;
      this.winning = false;
    },
    handelRecord() {
      this.modal = true;
      this.record = true;
      this.getHistory(0);
      this.active = 0;
    },
    // 设置数字成数组 123 => [1, 2, 3]
    setNums(num) {
      let str = num + "";
      let nums = [];
      for (let s of str) {
        nums.push(+s);
      }
      return nums;
    },
  },
};
</script>
<style scoped>
@import "./index.css";
</style>

